/*
 * @Author: lichao 1246877006@qq.com
 * @Date: 2024-09-25 15:11:17
 * @LastEditors: lichao 1246877006@qq.com
 * @LastEditTime: 2024-09-25 18:22:22
 * @FilePath: \algorithm\hello-algo\4 数组与链表\4.3 列表.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 列表类
class MyList {
    #arr = new Array()
    #capacity = 10
    #size = 0
    #extendRatio = 2

    constructor() {
        this.#arr = new Array(this.#capacity)
    }

    get size() {
        return this.#size
    }

    capacity() {
        return this.#capacity
    }

    get(index) {
        if(index < 0 || index >= this.#size) throw new Error('索引越界')
        return this.#arr[index]
    }

    set(index, num) {
        if(index < 0 || index >= this.#size) throw new Error('索引越界')
        this.#arr[index] = mum
    }

    add(num) {
        if(index < 0 || index >= this.#size) throw new Error('索引越界')
        this.#arr[this.#size] = num
        this.#size++
    }

    insert(index, num) {
        if(index < 0 || index >= this.#size) throw new Error('索引越界')
        if(this.#size === this.#capacity) {
            this.extendCapacity()
        }
        for(let i = this.#size - 1; i >= index; i--) {
            this.#arr[i + 1] = this.#arr[i] 
        }
        this.#arr[index] = num
        this.#size++
    }

    remove(index) {
        if(index < 0 || index >= this.#size) throw new Error('索引越界')
        const num = this.#arr[index]
        for(let i = index; i < this.#size - 1; i++) {
            this.#arr[i] = this.#arr[i - 1]
        }
        this.#size--
        return num
    }

    extendCapacity() {
        // 对数组进行 extendRatio 倍进行扩容
        this.#arr = [...this.#arr, ...new Array(this.capacity() * this.#extendRatio - 1)]
        this.#capacity = this.#arr.length
    }

    toArray() {
        const size = this.size
        const arr = new Array(size)
        for(let i = 0; i < size; i++) {
            arr[i] = this.get(i)
        }
        return arr
    }
}